﻿/************************************************
* Copyright (C) 2011 东北农业大学(NEAU) 版权所有。
* 文件名：
* 版本号：
* 文件功能描述：
* 作者：
* 创建日期:
* 版本号：
* 修改人：
* 修改日期：
* 修改描述：
************************************************/
Ext.BLANK_IMAGE_URL = '/script/ext/resources/images/s.gif';
Ext.onReady(function () {
    //初始化快速提示
    Ext.QuickTips.init();
    //将提示显示在form属性旁边
    Ext.form.Field.prototype.msgTarget = "side";
    //创建根节点
    var DepmetTreeRoot = new Ext.tree.AsyncTreeNode({ text: '部门树', id: 'DepmetTreeRoot', expanded: true, leaf: false });
    //创建树面板
    var DepmetTree = new Ext.tree.TreePanel({
        loader: new Ext.tree.TreeLoader({ dataUrl: "SERVER/user/DepmetTree.aspx?r=" + new Date().getTime() }),
        id: 'DepmetTree',
        region: 'west',
        width: 140,
        minSize: 140,
        margins: '5 0 5 5',
        cmargins: '5',
        bodyStyle: "padding:2px;",
        title: "公司/部门",
        split: true,
        rootVisible: false,
        lines: true,
        autoScroll: true,
        animate: true,
        collapsible: true,
        containerScroll: true,
        tbar: [{ iconCls: 'icon-expand-all',
            tooltip: '全部展开',
            handler: function () { DepmetTreeRoot.expand(true); }
        }, { iconCls: 'icon-collapse-all',
            tooltip: '全部折叠',
            handler: function () { DepmetTreeRoot.collapse(true); }
        }, { iconCls: 'icon-add',
            tooltip: '添加同级',
            handler: function () {
                var selectNode = DepmetTree.getSelectionModel().getSelectedNode();
                DepmetAdd(DepmetTree, DepmetTreeRoot, selectNode, true);
            }
        }, { iconCls: 'icon-add',
            tooltip: '添加子集',
            handler: function () {
                var selectNode = DepmetTree.getSelectionModel().getSelectedNode();
                DepmetAdd(DepmetTree, DepmetTreeRoot, selectNode, false);
            }
        }, { iconCls: 'icon-edit',
            tooltip: '编辑',
            handler: function () {
                var selectNode = DepmetTree.getSelectionModel().getSelectedNode();
                if (selectNode) {
                    Ext.Msg.prompt("编辑公司/部门", "请输入新公司/部门名称", function (btn, text) {
                        if (btn == "ok") {
                            if (text != "") {
                                Ext.Ajax.request({
                                    url: "SERVER/User/DepmetAdd.aspx",
                                    method: 'POST',
                                    params: { text: text, nodeId: selectNode.id },
                                    success: function (response) {
                                        var json = Ext.util.JSON.decode(response.responseText);
                                        if (json.success) {
                                            Ext.Msg.alert("提示", json.msg);
                                            DepmetTree.loader.load(DepmetTreeRoot);
                                        } else {
                                            Ext.Msg.alert("错误", json.msg);
                                        }
                                    }
                                });
                            } else {
                                Ext.Msg.alert("提示", "请输入名称");
                            }
                        }
                    }, "", "", selectNode.text);
                }
            }
        }, { iconCls: 'icon-del',
            tooltip: '删除',
            handler: function () {
                var selectNode = DepmetTree.getSelectionModel().getSelectedNode();
                if (selectNode) {
                    Ext.Msg.confirm("确认提示", "确认要删除" + selectNode.text + "?", function (btn) {
                        if (btn == "yes") {
                            Ext.Ajax.request({
                                url: "SERVER/User/DepmetDel.aspx",
                                method: 'POST',
                                params: { nodeId: selectNode.id },
                                success: function (response) {
                                    var json = Ext.util.JSON.decode(response.responseText);
                                    if (json.success) {
                                        Ext.Msg.alert("提示", json.msg);
                                        DepmetTree.loader.load(DepmetTreeRoot);
                                    } else {
                                        Ext.Msg.alert("错误", json.msg);
                                    }
                                }
                            });
                        }
                    }, "", "", selectNode.text);
                }
            }
        }]
    });
    DepmetTree.setRootNode(DepmetTreeRoot);
    DepmetTree.on('click', function (node, e) {
        if (node) {
            groupStore.load({ params: { start: 0, limit: pageSize, depmetId: node.id} });
        }
    });
    //定义请求参数
    var proxy = new Ext.data.HttpProxy({ url: "SERVER/User/UserList.aspx?r=" + new Date().getTime() });
    //定义数据模型
    var UserInfo = new Ext.data.Record.create([
                        { name: 'ID', type: 'int', mappging: "ID" },
                        { name: 'Account', type: 'string', mappging: "Account" },
                        { name: 'Name', type: 'string', mappging: "Name" },
                        { name: 'Password', type: 'string', mappging: "Password" },
                        { name: 'EName', type: 'string', mappging: "EName" },
                        { name: 'Email', type: 'string', mappging: "Email" },
                        { name: 'DepartmentID', type: 'string', mappging: "DepartmentID" },
                        { name: 'DutyID', type: 'int', mappging: "DutyID" },
                        { name: 'LastLoginTime', type: 'date', mappging: "LastLoginTime" }
                        ]);
    //创建阅读器
    var reader = new Ext.data.JsonReader({ totalProperty: "Count", root: "List" }, UserInfo);
    var formReader = new Ext.data.JsonReader({}, UserInfo);
    //创建数据源
    var groupStore = new Ext.data.GroupingStore({
        proxy: proxy,
        reader: reader,
        sortInfo: { field: 'ID', direction: 'DESC' }
    });
    //设置每页条数
    var pageSize = 30;
    var cookiePageSize = parseInt(Ext.util.Cookies.get("pageSize"));
    if (cookiePageSize) { pageSize = cookiePageSize; }
    //加载数据源
    groupStore.load({ params: { start: 0, limit: pageSize} });
    //创建选择列模型
    var sm = new Ext.grid.CheckboxSelectionModel();
    //定义列模型
    var cm = new Ext.grid.ColumnModel([
            new Ext.grid.RowNumberer(),
            sm,
            { id: 'id', header: '编号', dataIndex: 'ID', width: 60, sortable: true },
            { id: 'account', header: '帐号', dataIndex: 'Account', width: 100, sortable: true },
            { id: 'account', header: '密码', dataIndex: 'Password', width: 100, hidden: true },
            { id: 'eName', header: '英文名', dataIndex: 'EName', width: 80, sortable: true },
            { id: 'name', header: '中文名', dataIndex: 'Name', width: 80, sortable: true },
            { id: 'departmentText', header: '公司/部门', dataIndex: 'DepartmentID', width: 100, sortable: true, renderer: function (v) { var str = Jxym.ajax.request("server/User/DepmetGetModel.aspx?depmetId=" + v); var json = Ext.util.JSON.decode(str); return json.Name; } },
            { id: 'dutyID', header: '职务', dataIndex: 'DutyID', width: 72, sortable: true, renderer: function (v) { var str = Jxym.ajax.request("server/User/DutiesGetModel.aspx?dutiesId=" + v); var json = Ext.util.JSON.decode(str); return json.Name; } },
            { id: 'lastLoginTime', header: '最后登陆时间', dataIndex: 'LastLoginTime', width: 72, sortable: true },
            { id: 'eamil', header: '电子邮箱', dataIndex: 'Email', width: 100, sortable: true }
            ]);

    //创建下[每页行数]拉框
    var comboBox = new Ext.form.ComboBox({
        width: 50,
        typeAhead: true,
        triggerAction: 'all',
        lazyRender: true,
        mode: 'local',
        title: "每页行数",
        emptyText: pageSize,
        store: new Ext.data.ArrayStore({
            fields: ['myId', 'displayText'],
            data: [[10, 10], [20, 20], [30, 30], [50, 50], [100, 100]]
        }),
        valueField: 'myId',
        displayField: 'displayText'
    }); comboBox.on("select", function (combo, record, index) {
        Ext.util.Cookies.set("pageSize", record.id);
        window.location.reload();
    });
    var grid = new Ext.grid.GridPanel({
        title: "用户列表",
        store: groupStore,
        border: true,
        margins: '5 0 5 0',
        region: 'center',
        autoExpandColumn: "eamil",
        loadMask: { msg: '正在努力的加载，请稍等片刻..' },
        view: new Ext.grid.GroupingView(),
        sm: sm,
        cm: cm,
        tbar: [{
            iconCls: 'icon-user_add-16',
            text: '添加',
            handler: function (btn) {
                viewport.items.get(2).expand();
                UserForm.getForm().reset();
                Ext.getCmp("saveBtn").setText("确认添加");
                UserForm.findByType('textfield')[1].focus(true, true);
            }
        }, {
            ref: '../removeBtn',
            iconCls: 'icon-user_delete-16',
            text: '删除',
            disabled: true,
            handler: function () {
                Ext.MessageBox.confirm("确认提示", "确认要删除所选行数据？", function (btn) {
                    if (btn == "yes") {
                        var s = grid.getSelectionModel().getSelections();
                        var delR = new Array();
                        var delRid = new Array();
                        for (var i = s.length - 1; i >= 0; i--) {
                            var r = s[i];
                            if (r.get('ID') != undefined) { delRid.push(r.get('ID')); delR.push(r); }
                        }
                        Ext.Ajax.request({
                            url: "SERVER/User/UserDel.aspx",
                            method: 'POST',
                            params: { id: delRid },
                            success: function (response) {
                                var json = Ext.util.JSON.decode(response.responseText);
                                if (json.success) {
                                    for (var i = 0; i < delR.length; i++) {
                                        if (json.ids.valueOf(delR[i].get('ID'))) { groupStore.remove(delR[i]) }
                                    }
                                    Ext.Msg.alert("提示", "已删除" + json.count + "行<br/>" + json.msg);
                                } else {
                                    Ext.Msg.alert("错误", json.error);
                                }
                            }
                        });
                    }
                });
            }
        }],
        bbar: new Ext.PagingToolbar({
            store: groupStore,
            pageSize: pageSize,
            displayInfo: true,
            prependButtons: true,
            items: ['每页行数', comboBox, '-'],
            displayMsg: "本页显示第{0}条到第{1}条数据，共{2}条",
            emptyMsg: "暂无记录"
        })
    });

    var DepmetComboBoxTree = new Ext.ux.ComboBoxTree({
        fieldLabel: "公司/部门",
        hiddenName: "department",
        name: "department",
        anchor: '100%',
        emptyText: "请选择公司/部门",
        editable: false,
        selectNodeModel: 'all',
        tree: {
            xtype: 'treepanel',
            lines: true, rootVisible: false, border: false,
            loader: new Ext.tree.TreeLoader({ dataUrl: 'SERVER/User/DepmetTree.aspx' }),
            root: new Ext.tree.AsyncTreeNode({ text: '公司/部门', id: "0", leaf: false })
        }
    });
    var DutiesComboBox = new Ext.form.ComboBox({
        name: "DutyID",
        anchor: '100%',
        fieldLabel: "所属职务",
        emptyText: "请选择职务",
        listEmptyText: "*暂无职务信息*",
        blankText: '请选择职务',
        hiddenName: "DutyID",
        triggerAction: 'all',
        forceSelection: true,
        editable: false,
        mode: 'remote',
        valueField: 'did',
        displayField: 'dname',
        store: new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({ url: "SERVER/User/DutiesList.aspx" }),
            reader: new Ext.data.JsonReader({}, [{ name: 'did', type: 'int', mapping: "ID" }, { name: 'dname', type: 'string', mapping: "Name"}]),
            autoLoad: true
        })
    });
    var RoleCheckboxGroup = new Ext.ux.form.CheckboxGroup({
        xtype: 'mycheckboxgroup',
        hiddenName: "RoleID",
        name: "RoleID",
        fieldLabel: "角色",
        listEmptyText: "*暂无角色信息*",
        emptyText: "请选择角色",
        editable: false,
        columns: 2,
        dataUrl: 'SERVER/role/RoleList.aspx',
        labelFiled: 'Name',
        valueFiled: 'ID'
    });
    var UserForm = new Ext.form.FormPanel({
        region: 'east',
        split: true,
        width: 240,
        minSize: 240,
        maxSize: 300,
        collapsible: true,
        margins: '5 5 5 0',
        cmargins: '5',
        title: "编辑信息",
        bodyStyle: "padding:10px 5px;",
        labelAlign: "right",
        labelWidth: 60,
        buttonAlign: "center",
        defaultType: "textfield",
        border: true,
        items: [new Ext.form.Hidden({ value: 0, name: 'ID' }),
                { name: "Account", allowBlank: false, regex: /^[a-zA-Z0-9_]{2,}$/, regexText: "帐号格式：字母、数字和下划线并且至少输入两个字符以上[必填]", fieldLabel: "登录帐号" },
                { name: "Password", allowBlank: false, fieldLabel: "登录密码", inputType: 'password' },
                { name: "Name", regex: /[\u4e00-\u9fa5]/, regexText: "只能输入中文!", allowBlank: false, fieldLabel: "中文名" },
                { name: "EName", fieldLabel: "英文名", regex: /[a-zA-Z0-9]/, regexText: "只能输入字母和数字!" },
                { name: "Email", fieldLabel: "电子邮箱", vtype: "email", allowBlank: false, invaildText: "输入结果无效" },
                    DepmetComboBoxTree, DutiesComboBox, RoleCheckboxGroup],
        buttons: [{
            id: "saveBtn",
            text: "确定",
            handler: function () {
                if (UserForm.form.isValid()) {
                    var params = { DepartmentID: DepmetComboBoxTree.getCtValue() };
                    UserForm.getForm().submit({
                        url: "server/User/UserAdd.aspx",
                        params: params,
                        success: function (form, action) {
                            Ext.Msg.alert("请求成功", action.result.msg, function () {
                                groupStore.load({ params: { start: 0, limit: pageSize, depmetId: params.DepartmentID} });
                            });
                        }, failure: function (form, action) { Ext.Msg.alert("请求失败", action); }
                    });
                }
            }
        }, {
            text: "重置",
            handler: function () { UserForm.getForm().reset(); }
        }]
    });

    //创建页面布局
    var viewport = new Ext.Viewport({ layout: 'border', items: [DepmetTree, grid, UserForm] }); viewport.items.get(2).collapse(); viewport.doLayout();
    //延时加载
    setTimeout(function () { Ext.get('loading').remove(); Ext.get('loading-mask').fadeOut({ remove: true }); }, 400);
    //有选择行启用删除按钮
    grid.getSelectionModel().on('selectionchange', function (sm) { grid.removeBtn.setDisabled(sm.getCount() < 1); });
    grid.on('rowclick', function (g, index, e) {
        viewport.items.get(2).expand();
        Ext.getCmp("saveBtn").setText("确认更新");
        var r = g.getSelectionModel().getSelected();
        UserForm.getForm().loadRecord(r);
        DepmetComboBoxTree.setCtValue(GetDepmetName(r.get("DepartmentID")), r.get("DepartmentID"));
        var vstr = Jxym.ajax.request("SERVER/role/RoleTree.aspx?userid=" + r.get("ID") + "&r=" + new Date().getTime());
        RoleCheckboxGroup.setValue(vstr);
        UserForm.doLayout();
    });
});
function showValue() {
    alert("显示值=" + DepmetComboBoxTree.getRawValue() + "  真实值=" + DepmetComboBoxTree.getValue());
}
function search() {
    var searchName = Ext.getDom('searchName').value;
    alert("查询字符串：" + searchName);
}